﻿using System;
using System.Collections.Generic;
using System.Text;
using WindowsLive.Writer.Api;
using Microsoft.Win32;

namespace WordpressFeaturedImagePlugin
{
    /// <summary>
    /// A BlogContext hold information about the current blog the user is selected on inside the Windows Live
    /// Writer.  It looks up extra information from the registery.
    /// </summary>
    public class BlogContext
    {
        /// <summary>
        /// Basic information about the selected blog
        /// </summary>
        public readonly IPublishingContext PublishingContext;

        /// <summary>
        /// A url to the endpoint for the selected blog that xml-rpc requests can be sent to
        /// </summary>
        public readonly string PostApiUrl;

        /// <summary>
        /// The username for the user's blog
        /// </summary>
        public readonly string Username;

        /// <summary>
        /// BlogId used to identify the blog through xml-rpc
        /// </summary>
        public readonly string BlogId;

        /// <summary>
        /// Path to where Windows Live Writer saves settings in the registery
        /// </summary>
        private const string WRITER_REGISTRY_KEY = @"Software\Microsoft\Windows Live\Writer\Weblogs";


        public BlogContext(IPublishingContext publishingContext)
        {
            PublishingContext = publishingContext;

            // Look through all the blogs in the registery to find the currently selected blog
            using (RegistryKey weblogs = Registry.CurrentUser.OpenSubKey(WRITER_REGISTRY_KEY))
            {
                string[] weblogIds = weblogs.GetSubKeyNames();
                foreach (string id in weblogIds)
                {
                    using (RegistryKey weblog = Registry.CurrentUser.OpenSubKey(WRITER_REGISTRY_KEY + "\\" + id))
                    {
                        // We can find the blog by matching up the url to the homepage
                        string url = weblog.GetValue("HomepageUrl") as string;
                        if (url == PublishingContext.HomepageUrl)
                        {
                            // Grab all the sub settings
                            PostApiUrl = weblog.GetValue("PostApiUrl") as string;
                            BlogId = weblog.GetValue("BlogId") as string;
                            using (RegistryKey creds = weblog.OpenSubKey("Credentials"))
                            {
                                Username = creds.GetValue("Username") as string;
                            }
                        }
                    }
                }
            }
        }
    }
}
